<template>
  <div>
    <NormalForm pageTitle="群SOP" :operateForm="queryForm" :formList="formList" :enumOpt="enumOpt" @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
    <div class="g-card">
      <div class="right-btn">
        <el-button type="primary" @click="goRoute" icon="el-icon-plus" v-hasPermi="['group:sop:add']">
          创建规则
        </el-button>
      </div>
      <div style="padding: 0 20px 20px 20px">
        <el-table v-loading="loading" :data="tableList" style="width: 100%" height="475">
          <el-table-column type="index" width="55" align="center" label="序号" />
          <el-table-column label="规则名称" align="center" show-overflow-tooltip prop="taskName"></el-table-column>
          <el-table-column label="执行群聊" prop="scrmGroupSopRelList" align="center">
            <template slot-scope="scope">
              <el-popover placement="top" trigger="hover" v-if="scope.row.scrmGroupSopRelList && scope.row.scrmGroupSopRelList.length > 1">
                <template>
                  <el-tag v-for="(m,n) in scope.row.scrmGroupSopRelList" :key="n">{{m.groupName}}</el-tag>
                </template>
                <div slot="reference" class="set-content">
                  <el-tag v-for="(m,n) in scope.row.scrmGroupSopRelList" :key="n">{{m.groupName}}</el-tag>
                </div>
              </el-popover>
              <div v-else> <el-tag v-for="(m,n) in scope.row.scrmGroupSopRelList" :key="n">{{m.groupName}}</el-tag></div>
            </template>
          </el-table-column>
          <el-table-column label="创建人" align="center" prop="createBy" show-overflow-tooltip />
          <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="160px">
            <template slot-scope="{ row }">
              <div>
                <el-switch v-model="row.status" :active-value="2" :inactive-value="1" @change="switchChange(row)">
                </el-switch>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <div class="option-span">
                <el-button size="mini" type="text" @click="detailRoute(row.taskId)"
                           v-hasPermi="['group:sop:query']">详情</el-button>
                <el-button size="mini" type="text" @click="editRoute(row.taskId)"
                           v-hasPermi="['group:sop:edit']">编辑</el-button>
                <el-button size="mini" type="text" @click="deleteItem(row.taskId)"
                           v-hasPermi="['group:sop:remove']">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
    </div>
    <dialog-text text="确认删除该群SOP？" :width.sync="dialogTextWidth" :visible.sync="visible" @confirm="deleteConfirm"></dialog-text>
  </div>
</template>
<script>
import DialogText from "@/components/DialogText.vue";
import { queryTaskList, groupChatList, deleteGroupSop, updateStatus } from "@/api/operate/groupSop";

export default {
  name: "groupSop",
  components: { DialogText },
  data() {
    return {
      queryForm: {
        taskName: "",
        deptId: null,
        chatId: null,
        createCodeList: [],
        dateRange: [],
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '规则名称',
          value: '',
          prop: 'taskName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '关联群聊',
          value: '',
          prop: 'chatId',
          type: 'SELECT',
          emunName: 'groupList'
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createCodeList',
          type: 'STAFF',
          emunName: ''
        },
        {
          label: '创建',
          value: [],
          prop: 'dateRange',
          type: 'DATE_RANGE',
          formate: 'yyyy-MM-dd',
          emunName: ''
        },
      ],
      enumOpt: {
        groupList: [],
      },
      total: 0,
      loading: false,
      tableList: [],
      visible: false,
      currentDeleteGroupTaskId: "",
      dialogTextWidth: '400px',
    };
  },
  mounted() {
    this.getDict();
    this.handleQuery();
  },
  methods: {
    getDict() {
      // 关联群聊列表
      groupChatList().then(res => {
        if (res.code == 200) {
          const arr = JSON.parse(JSON.stringify(res.data)) || []
          const uniqueArr = arr.reduce((acc, current) => {
            const x = acc.find(item => item.chatId === current.chatId);
            if (!x) {
              return acc.concat([{ ...current, dictLabel: current.groupName, dictValue: current.chatId}]);
            } else {
              return acc;
            }
          }, []);
          this.enumOpt.groupList = uniqueArr
          // res.data.forEach(item => {
          //   this.enumOpt.groupList.push({ dictLabel: item.groupName, dictValue: item.chatId });
          // });
        }
      })
    },
    // 重置
    handleReset() {
      this.queryForm = {
        taskName: "",
        deptId: null,
        chatId: null,
        createCodeList: '',
        dateRange: [],
        pageNum: 1,
        pageSize: 20,
      };
      this.queryTaskListFn();
    },
    // 查询
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.queryTaskListFn();
    },
    queryTaskListFn() {
      let params = {
        taskName: this.queryForm.taskName,
        createCodeList: this.queryForm.createCodeList + '',
        deptId: this.queryForm.deptId,
        chatId: this.queryForm.chatId,
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
        startDate: this.queryForm.dateRange?.[0],
        endDate: this.queryForm.dateRange?.[1],
        sendEdition: '1'
      };
      this.loading = true;
      queryTaskList(params).then((res) => {
        if (res.code === 200) {
          this.tableList = res.rows || [];
          this.total = res.total || 0;
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    // 翻页
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.queryTaskListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.queryTaskListFn()
    },
    // 新增规则
    goRoute() {
      this.$router.push({ name: "CreateRule" , query: { activeName: '1'}});
    },
    // 状态修改
    switchChange(row) {
      this.loading = true
      const { taskId, status } = row
      updateStatus({ taskId, status })
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg || "状态修改成功")
            this.queryTaskListFn()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 详情
    detailRoute(id) {
      this.$router.push({
        name: "GroupSopDetail",
        query: {
          taskId: id,
          fromDetail: true,
          activeName: '1'
        },
      });
    },
    // 编辑
    editRoute(id) {
      this.$router.push({
        name: "GroupSopEdit",
        query: {
          taskId: id,
          fromDetail: false,
          activeName: '1'
        },
      });
    },
    deleteItem(id) {
      this.currentDeleteGroupTaskId = id
      this.visible = true
    },
    deleteConfirm() {
      this.loading = true
      deleteGroupSop(this.currentDeleteGroupTaskId)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg || "删除成功")
            this.handleQuery()
          }
        })
        .finally(() => {
          this.loading = false
          this.visible = false
        })
    }
  },
};
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";
::v-deep .el-table th.el-table__cell.is-leaf,
.el-table td.el-table__cell {
  border-bottom: none !important;
}

::v-deep .el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important;
}

::v-deep .el-tooltip {
  overflow: hidden; //超出隐藏
  white-space: nowrap; //不折行
  text-overflow: ellipsis; //溢出显示省略号
}
</style>
